package com.whzm.service.Impl;

import com.whzm.mapper.ResourcesMapper;
import com.whzm.mapper.UserMapper;
import com.whzm.pojo.Resources;
import com.whzm.pojo.User;
import com.whzm.pojo.vo.FlowMatchVo;
import com.whzm.pojo.vo.ResourcesListVo;
import com.whzm.service.WorkService;
import com.whzm.util.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
@SuppressWarnings("all")
public class WorkServiceImpl implements WorkService {
    @Autowired
    ResourcesMapper resourcesMapper;

    @Autowired
    UserMapper userMapper;

    /**
     * 根据userId获取资源列表
     * @param userId
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public List<Resources> getResourcesByUserId(String userId) {
        return resourcesMapper.getResourcesByUserId(userId);
    }

    /**
     * 根据userId获取符合推荐资格的资源
     * @param userId
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public ResponseEntity getTrueResourcesByOwnResourcesId(String userId,Integer page,Integer pageSize) {
        //根据自身userId获取自己发布的未匹配的资源
        List<Resources> myResources = getResourcesByUserId(userId);
        List<Resources> resources = new ArrayList<>();
        List<ResourcesListVo> resourcesListVoList = new ArrayList<>();
        List<ResourcesListVo> resourcesListVos = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();

        //对每个自己发布的需求进行匹配推荐
        for(Resources resource : myResources){
            String resourceId = resource.getId();
            Integer resourceType = resource.getType()==1?2:1;

            //取出资源落地类型和合作方式都符合的资源数据
            List<String> resourcesId = getCommonResourcesId(getResourcesByImplementation(resourceId),getResourcesByCooperation(resourceId));

            //将参数封装成一个map传入mapper
            map.put("resourcesId",resourcesId);
            map.put("type",resourceType);
            map.put("userId",userId);
            List<ResourcesListVo> resourcesList = resourcesMapper.getRecommendationResources(map);

            for(ResourcesListVo resourcesListVo : resourcesList){
                resourcesListVos.add(resourcesListVo);
            }
        }
        //分页代码(有问题)
        Integer start = (page - 1)*pageSize,end = (page - 1)*pageSize + pageSize;


        if(start <resourcesListVos.size()){
            if(end > resourcesListVos.size()){
                end = resourcesListVos.size();
            }

            for(int i = start;i < end;i++){
                resourcesListVoList.add(resourcesListVos.get(i));
            }
        }
        return ResponseEntity.pageSuccess(200,"推荐资源成功",resourcesListVoList,resourcesListVos.size());
    }

    /**
     * 得到已发布的资源
     * @param userId
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public ResponseEntity getPublishedResources(String userId,Integer page,Integer pageSize) {
        List<Resources> resources = resourcesMapper.getPublishedResources(userId);
        List<ResourcesListVo> resourcesListVos = new ArrayList<>();
        List<ResourcesListVo> resourcesListVoList = new ArrayList<>();
        Integer start = (page - 1)*pageSize,end = (page - 1)*pageSize + pageSize;

        for(Resources resource : resources){
            resourcesListVos.add(resourcesMapper.getResourcesVoByRId(resource.getId()));
        }

        if(resourcesListVos.size() > 0){
            if(start <resourcesListVos.size()){
                if(end > resourcesListVos.size()){
                    end = resourcesListVos.size();
                }

                for(int i = start;i < end;i++){
                    resourcesListVoList.add(resourcesListVos.get(i));
                }
            }
            return ResponseEntity.pageSuccess(200,"成功获取已发布资源",resourcesListVoList,resourcesListVos.size());
        }

        return ResponseEntity.tipsSuccess(500,"fail");
    }

    /**
     * 根据用户id，获取待匹配资源
     * @param userId
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public ResponseEntity getToBeMatchResources(String userId) {
        Map<String,Object> maps = new HashMap<>();
        List<FlowMatchVo> flowMatches = resourcesMapper.getToBeMatchResources(userId);

        if(flowMatches == null || flowMatches.size() == 0){
            return ResponseEntity.tipsSuccess(500,"未找到待匹配资源");
        }

        //获取FlowMatchVo中间类信息
        for (int i = 0;i < flowMatches.size();i++) {
            User advertiser = userMapper.getUserById(flowMatches.get(i).getAdvertiserId());
            User flower = userMapper.getUserById(flowMatches.get(i).getFlowerId());
            Resources advertiseResources = resourcesMapper.getResourcesByRId(flowMatches.get(i).getAdvertiseId());
            Resources flowResources = resourcesMapper.getResourcesByRId(flowMatches.get(i).getFlowId());

            flowMatches.get(i).setAdvertiserName(advertiser.getUsername());
            flowMatches.get(i).setAdvertiserWechat(advertiser.getWechat());
            flowMatches.get(i).setFlowerName(flower.getUsername());
            flowMatches.get(i).setFlowerWechat(flower.getWechat());
            flowMatches.get(i).setAdvertiseCompany(advertiseResources.getCompany());
            flowMatches.get(i).setAdvertiseName(advertiseResources.getName());
            flowMatches.get(i).setFlowCompany(flowResources.getCompany());
            flowMatches.get(i).setFlowName(flowResources.getName());
        }

        return ResponseEntity.entitySuccess(200,"查找待匹配资源成功",flowMatches);
    }

    /**
     * 修改匹配表中，匹配数据的状态
     * @param flowMatchId
     * @param type
     * @return
     */
    @Override
    public ResponseEntity modifyMatchStatus(String flowMatchId,Integer type,String advertiseId,String flowId) {
        Map<String,Object> map = new HashMap<>();
        map.put("matchId",flowMatchId);
        map.put("matchStatus",type);

        int result = resourcesMapper.updateFlowMatch(map);
        if(result != 0){
            //同意匹配，修改资源表中status
            if(type == 1){
                resourcesMapper.updateResourceStatus(flowId);
                resourcesMapper.updateResourceStatus(advertiseId);
            }

            return ResponseEntity.tipsSuccess(200,"操作成功");
        }else{
            return ResponseEntity.tipsSuccess(500,"匹配失败");
        }
    }

    /**
     * 添加一条流量信息
     * @param flowMatchVo
     * @return
     */
    @Override
    public ResponseEntity addFlowMatchInfo(FlowMatchVo flowMatchVo) {
        flowMatchVo.setMatchStatus(0);
        flowMatchVo.setId("R" + String.valueOf(System.currentTimeMillis() + "" + (int) (Math.random() * 100)).substring(3));
        Integer result = resourcesMapper.addFlowMatchInfo(flowMatchVo);

        if (result != 0) {
            return ResponseEntity.tipsSuccess(200, "success");
        } else {
            return  ResponseEntity.tipsSuccess(500, "fail");
        }
    }

    /**
     * 首页置顶
     */
    @Override
    public ResponseEntity queryTop() {
        List<ResourcesListVo> resourcesListVos=new ArrayList<>();
        //根据购买的置顶等级降序，时间降序
        List<ResourcesListVo> resourcesListVoList= resourcesMapper.queryTop();
        //将时间过期的去掉
        for(int i=0;i<resourcesListVoList.size();i++){
            String aliveTime=resourcesListVoList.get(i).getAliveTime();
            String vcreateTime=resourcesListVoList.get(i).getVcreateTime();
            //当前时间毫秒数
            long nowTime=System.currentTimeMillis();
            //申请时间的毫秒数
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date time1 = null;
            try {
                time1 = sdf.parse(vcreateTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            long time2 = time1.getTime();
            //存活时间
            long atime=Long.parseLong(aliveTime);
            if(nowTime-time2 > atime){
                resourcesListVoList.remove(i);
                i--;
            }
        }
        //取出前七条
        if(StringUtils.isEmpty(resourcesListVoList)){
            return  ResponseEntity.tipsSuccess(400,"查询失败");
        }
        if(resourcesListVoList.size()>=5){
            for (int i=0;i<5;i++) {
                resourcesListVos.add(resourcesListVoList.get(i));
            }
        }else{
            for (ResourcesListVo resourcevo:resourcesListVoList) {
                resourcesListVos.add(resourcevo);
            }
        }
        return ResponseEntity.entitySuccess(200,"查询成功",resourcesListVos);
    }

    /**
     * 根据当前资源类型，去数据库中获取落地方式符合的其他资源id
     * @param resourcesId
     * @return
     */
    private List<String> getResourcesByImplementation(String resourcesId) {
        return resourcesMapper.getResourcesByImplementation(resourcesId);
    }

    /**
     * 根据当前资源类型，去数据库中获取合作方式符合的其他资源
     * @param resourcesId
     * @return
     */
    private List<String> getResourcesByCooperation(String resourcesId) {
        return resourcesMapper.getResourcesByCooperation(resourcesId);
    }

    /**
     * 得到两个resourcesId列表的交集
     * @return
     */
    private List<String> getCommonResourcesId(List<String> rList1, List<String> rList2){
        if(rList1 != null && rList2 != null){
            //取二者的交集
            rList1.retainAll(rList2);
            return rList1;
        }else{
            System.out.println("有空指针");
            return null;
        }
    }
}
